﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XXF.BaseService.ServiceCenter.Client.ClientPool
{
    /// <summary>
    /// 客户端连接池
    /// </summary>
    public class ClientPoolProvider
    {
        private static Dictionary<BaseClientConfig, BaseClientPool> _pools = new Dictionary<BaseClientConfig, BaseClientPool>();
        private static object _lockpool = new object();

        public T GetPool<T>(BaseClientConfig config) where T : BaseClientPool
        {
            if (_pools.ContainsKey(config))
            {
                return _pools[config] as T;
            }
            lock (_lockpool)
            {
                if (_pools.ContainsKey(config))
                {
                    return _pools[config] as T;
                }
                if (config.ServiceType == SystemRuntime.EnumServiceType.Thrift)
                {
                    var thriftconfig = new ThriftClientConfig()
                    {
                        Host = config.Host,
                        Port = config.Port,
                        MaxActive = 500,
                        MaxIdle = 50,
                        MinIdle = 2,
                        ServiceType = SystemRuntime.EnumServiceType.Thrift,
                        ValidateOnBorrow = true,
                        ValidateOnReturn = false
                    };
                    BaseClientPool pool = new ThriftClientPool(thriftconfig);
                    _pools.Add(thriftconfig, pool);
                    return _pools[thriftconfig] as T;
                }
                else
                {
                    throw new ServiceCenter.SystemRuntime.ServiceCenterException("不支持该服务类型:" + config.ServiceType.ToString());
                }
            }
        }

        public void Dispose()
        { }
    }
}
